package motionblur;

import java.awt.DisplayMode;
import java.awt.GraphicsEnvironment;
import java.util.Random;

public class Ball implements Runnable {
	
	private int x, y, width, height;
	private int move_x, move_y;
	private DisplayMode dm = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();

	public Ball(int x, int y, int width, int height) {
		super();
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		generateRandomMove();
		(new Thread(this)).start();
	}

	public int getX() {
		return x - getWidth()/2;
	}

	public int getY() {
		return y - getHeight()/2;
	}
	
	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}
	
	public void run() {
		while(true)	{
			handleCollision();
			move();
			try { Thread.sleep(5); } catch (InterruptedException e) {}	
		}
	}
	
	private void move() {
		x = x + move_x;
		y = y + move_y;
	}
	
	private void generateRandomMove() {
		Random random = new Random();
		move_x = random.nextInt(10) + 1;
		if(random.nextInt(2) == 0) {
			move_x = -move_x;
		}
		move_y = random.nextInt(10) + 1;
		if(random.nextInt(2) == 0) {
			move_y = -move_y;
		}
		
	}
	
	private void recalcMoveAngleX() {
		move_x = -move_x;
	}
	
	private void recalcMoveAngleY() {
		move_y = -move_y;
	}
	
	private void handleCollision() {
		if(getY() <= 0 || getY() + getHeight()/2 >= dm.getHeight()) {
			recalcMoveAngleY();
		} 
		if(getX() <= 0 || getX() + getWidth()/2 >= dm.getWidth()) {
			recalcMoveAngleX();
		}
	}

}
